//
//  MLUUID.m
//  CustomerPo
//
//  Created by molon on 9/16/14.
//  Copyright (c) 2014 molon. All rights reserved.
//

#import "MLUUID.h"
#import <SSKeychain.h>
#import "NSString+MLKit.h"

#define kServiceName @"uuid"
@interface MLUUID()

@end

@implementation MLUUID

+ (NSString*)UUID
{
    //从keychain里找到记录的UUID
    NSString *uuid = [MLUUID getUUIDFromKeychain];
    if ([NSString IsNilOrEmpty:uuid]) {
        uuid = [[UIDevice currentDevice].identifierForVendor UUIDString];
        [MLUUID setUUIDIntoKeychain:uuid];
    }
    return uuid;
}

+ (NSString*)serviceName
{
    NSString *serviceName = [[NSBundle mainBundle] bundleIdentifier]?:@"";
    return [serviceName stringByAppendingString:[NSString stringWithFormat:@".molon.%@",kServiceName]];
}

+ (NSString*)getUUIDFromKeychain
{
    NSString *serviceName = [self serviceName];
    
    //account也用和服务名一样的算了，简单
    return [SSKeychain passwordForService:serviceName account:serviceName];
}

+ (BOOL)setUUIDIntoKeychain:(NSString*)uuid
{
    NSString *serviceName = [self serviceName];
    
    if ([NSString IsNilOrEmpty:uuid]) {
        return [SSKeychain deletePasswordForService:serviceName account:serviceName];
    }
    return [SSKeychain setPassword:uuid forService:serviceName account:serviceName];
}

@end
